package com.jshop.msg.socket;

import com.jshop.common.result.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jon
 * @date 2020/1/15 15:13
 */
@ServerEndpoint("/socketServer/{sid}")
@Component
public class SocketServer {
    private static Logger logger = LoggerFactory.getLogger(SocketServer.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static ConcurrentHashMap<Integer, SocketServer> websocketList = new ConcurrentHashMap<>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    //接收sid
    private Integer sid = 0;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public CommonResult onOpen(Session session, @PathParam("sid") Integer sid) {
        this.session = session;
        //加入set中
        websocketList.put(sid, this);
        //在线数加1
        addOnlineCount();
        logger.info("有新窗口开始监听:" + sid + ",当前在线人数为" + getOnlineCount());
        this.sid = sid;
        return CommonResult.successMsg("连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public static void onClose(@PathParam("sid") Integer sid) {
        websocketList.remove(sid);
        System.out.println(websocketList.size());
        subOnlineCount();           //在线数减1
        logger.info("有一连接关闭！当前在线人数为" + getOnlineCount() + "关闭的标识 sid:" + sid);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("收到来自窗口" + sid + "的信息:" + message);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static void sendInfo(String message, Integer sid) throws IOException {
        for(Map.Entry<Integer, SocketServer> entry : websocketList.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            if (entry.getValue() != null) {
                entry.getValue().sendMessage(message);
            }
        }

    }


    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        SocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        SocketServer.onlineCount--;
    }


}
